<template>
	<view>
		
		<view style="width: 100%; height: 35px;">
			<view class="load" @click="addproduct">
				<text style="font-size: 13px;">发布</text>
			</view>
		</view>
		
		<uni-section title="商品名称" type="line">
			<textarea v-model="product.name" placeholder="(必填)" style="width: 100%; border: 3px solid #efefef; height: 25px; margin-bottom: 9px;"></textarea>
		</uni-section>
		
		<uni-section title="商品描述" type="line">
			<textarea v-model="product.description" placeholder="对于产品的介绍,出售原因,产品的破损程度等信息...(必填)" style="width: 90%; margin: auto; border: 3px solid #efefef; height: 120px; margin-bottom: 9px;"></textarea>
		</uni-section>
		
		<uni-section title="商品图片" type="line">
			<view class="photo">
				<view v-for="(item, i) in photos" :key="i" style="position: relative; width: 28%; border: 1px solid #efefef; height: 90px; margin-right: 10px; margin-bottom: 5px;" >
					<image :src="item" style="width: 100%; height: 90px;"></image>
					<view class="deleteBtn" @click="delete_photo" :data-path="item">X</view>
				</view>
				<view @click="get_photo" style="width: 28%; border: 1px solid #efefef; height: 90px; display: flex; justify-content: center; align-items: center;">
					<text style="font-size: 14px;">+添加图片</text>
				</view>
			</view>
		</uni-section>
		
		<view style="margin-bottom: 9px;">
			<uni-section title="分类" type="line">
				<uni-data-select v-model="value" :localdata="range"></uni-data-select>
			</uni-section>
		</view>
		
		
		<uni-section title="联系方式" type="line">
			<uni-data-select v-model="value2" :localdata="range2"></uni-data-select>
			<textarea v-model="product.contact_way" placeholder="(必填)" style="width: 100%;border: 3px solid #efefef; height: 22px; margin-bottom: 9px;"></textarea>
		</uni-section>
		
		<uni-section title="地址" type="line">
		  <uni-data-select v-model="value1" :localdata="range1"></uni-data-select>
		</uni-section>
		
		<view style=" border: 2px solid #efefef; margin: 15px 0; height: 30px; display: flex; align-items: center; justify-content: space-between;">
			<text>￥价格：</text>		
			<input type="digit" v-model="product.price" @input="oninput" :maxlength="moneyMaxLeng" placeholder="0.00" style="width: 25%;"/>
		</view>

	</view>
</template>

<script>
	import { mapState, mapMutations, mapGetters } from 'vuex'
	let that = null
	export default {
		data() {
			return {
				moneyMaxLeng: 4,//规定最大可输入的长度
				product:{
					"openid":"",
					"price":"",
					"name":"",
					"description":"",
					"pictures": [],
					"date":Date().toString(),
					"address":"",
					"category":"",
					"contact_way_category":"",
					"contact_way":"",
					"photos": []
				},
				photos:[],
				value: 1,
				range: [
				  { value: 1, text: "教材" },
				  { value: 2, text: "电子产品" },
				  { value: 3, text: "交通" },
				  { value: 4, text: "衣服" },
				  { value: 5, text: "运动" },
				  { value: 6, text: "食物" },
				  { value: 7, text: "文具" },
				  { value: 8, text: "生活用品" },
				  { value: 9, text: "其他" },
				],
				value1: 1,
				range1: [
				  { value: 1, text: "紫菘" },
				  { value: 2, text: "沁苑" },
				  { value: 3, text: "韵苑" },
				],
				value2: 1,
				range2: [
				  { value: 1, text: "QQ" },
				  { value: 2, text: "VX" },
				  { value: 3, text: "手机号" },
				],
				seconds: 3
			};
		},
		
		onShow() {
			this.setCartNum()
			
		},
		computed: {
			...mapState('m_cart', ['cart']),
			...mapGetters('m_cart', ['total']),
			...mapGetters('m_cart', ['pay_total']),
			...mapState('m_my', ['user']),
			...mapState('m_my', ['user_id']),
			
		},
		methods: {
			...mapMutations('m_my', ['updateReaddress']),

			setCartNum() {
				if(this.pay_total == 0){
					uni.hideTabBarRedDot({
						index: 3,
					})
				}else{
					uni.setTabBarBadge({
						index: 3,
						text: this.pay_total + ''
					})
				}		
			},
			async get_photo() {
				that = this
				uni.chooseImage({
					count:9,
					sourceType: ['album'],
					
					success(res){		
						for(let i = 0 ;i < res.tempFilePaths.length;i++){
						 	let path = res.tempFilePaths[i]
							let t = [path]
							that.photos = [...that.photos, ...t]
						}					
					},
					fail(res){
						console.log(res)
					}
				})
			},		
			oninput(e) {
				this.$nextTick(() => {
				  let val = e.target.value.toString();
				  val = val.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
				  val = val.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
				  val = val.replace(/^0+\./g, '0.');
				  val = val.match(/^0+[1-9]+/) ? val = val.replace(/^0+/g, '') : val
				  val = (val.match(/^\d*(\.?\d{0,2})/g)[0]) || ''

				  if (val.includes(".")) {
					let numDian = val.toString().split(".")[1].length;
					if (numDian === 2) {
					  this.moneyMaxLeng = val.length;
					}
				  } else {
					this.moneyMaxLeng = 8;
				  }
				  this.writeMoney = val;
				});
			},
			async addproduct(){
				that = this
				
				if(JSON.stringify(this.user) == '{}') return this.delay_message()
				
				if(that.value1>=1 &&that.value1<=3){
					that.product.address=that.range1[that.value1-1].text
				}
				else{
					that.product.address=""
				}
				if(that.value>=1&&that.value<=9){
					that.product.category=that.range[that.value-1].text
				}
				else{
					that.product.category=""
				}
				if(that.value2>=1&&that.value2<=3){
					that.product.contact_way_category=that.range2[that.value2-1].text
				}
				else{
					that.product.contact_way_category=""
				}
				if(!that.product.price) return uni.showToast({
						title: '您的商品价格未填完！\n 请填完后，再发布！',
						duration: 1500,
						icon: 'none'
					})
				
				if(!that.product.name) return uni.showToast({
						title: '您的商品名称未填完！\n 请填完后，再发布！',
						duration: 1500,
						icon: 'none'
					})
				
				if(!that.product.description) return uni.showToast({
						title: '您的商品描述未填完！\n 请填完后，再发布！',
						duration: 1500,
						icon: 'none'
					})
					
				if(that.photos.length == 0) return uni.showToast({
						title: '您的商品图片未添加！\n 请添加后，再发布！',
						duration: 1500,
						icon: 'none'
					})
				if(!that.product.category) return uni.showToast({
						title: '您的商品分类未选择！\n 请选择后，再发布！',
						duration: 1500,
						icon: 'none'
					})
				if(!that.product.contact_way_category) return uni.showToast({
						title: '您的联系方式未选择！\n 请选择后，再发布！',
						duration: 1500,
						icon: 'none'
					})
				if(!that.product.contact_way) return uni.showToast({
						title: '您的联系方式未填完！\n 请填完后，再发布！',
						duration: 1500,
						icon: 'none'
					})	
				if(!that.product.address) return uni.showToast({
						title: '您的地址未选择！\n 请选择后，再发布！',
						duration: 1500,
						icon: 'none'
					})
				this.product.date=Date().toString();
				for(let i=0;i<that.photos.length;i++){
					let path=that.photos[i]
					var j=0;
					for(j=String(path).length-1;path[j]!='.';j--);
					let res = await uniCloud.uploadFile({
						filePath:path,
						cloudPath:Date.now() + String(path).slice(j)
					})
					that.product.pictures = [...that.product.pictures, ...[res.fileID]]
				}
				that.product.photos = this.photos
				that.product.openid = this.user_id
			
				that.product.date=Date().toString()
				const db = uniCloud.database();
				db.collection('category').add(that.product).then(e=>{
					console.log(that.product)
					that.photos=[]
					that.product={
						"openid":"",
						"name":"",
						"price":"",
						"pictures":[],
						"date":that.product.date=Date().toString(),
						"description":"",
						"contact_way":"",
						"photos":[]
					}
				})
				
				
				uni.showToast({
					title:'发布成功！',
					duration:1500,
					icon:'success'
				})
			},
			delete_photo(e) {
				let index = this.photos.indexOf(e.target.dataset.path)
				if (index > -1) {
				  this.photos.splice(index, 1)
				}
			},
			delay_message() {
				this.show_tips(this.seconds)
				this.timer = setInterval(() => {
					this.seconds -- 
					if(this.seconds <= 0) {
						clearInterval(this.timer)
						uni.switchTab({
							url: '/pages/my/my',
							success: () => {
								this.updateReaddress({
									openType: 'switchTab',
									from: '/pages/add/add'
								})
							}
						})
						return this.seconds = 3
					}			
					this.show_tips(this.seconds)
				}, 750)
			},
			show_tips(n) {
				uni.showToast({
					title: '请先登录!\n' + n + '秒后自动进入登录界面',
					duration: 1500,
					icon:'none'
				})
			},
		}
	}
</script>

<style lang="scss">
	
	page {
		background-color: white;
	}
	
	.load {
		text-align:center;
		float: right; 
		background-color: #84AF9B; 
		width: 18%; 
		margin-top: 10px; 
		margin-right: 5px;
		height: 25px; 
		color: white; 
		border-radius: 25px;
	}

	.photo {
		display: flex;
		width: 90%;
		margin: auto;
		margin-top: 10px;
		flex-wrap: wrap;
		margin-bottom: 9px;
	}
	
	.deleteBtn{
	  position: absolute;
	  top:-6px;
	  right: -4px;
	  background-color: #efefef;
	  width: 20px;
	  height: 20px;
	  border-radius: 50%;
	  color: white;
	  text-align: center;
	  line-height: 20px;
	}
	
</style>
